<template>
  <div class="bg-white shadow-md p-4">
    <Navigation :homeRoute="homeRoute" :currentPage="currentPage" />
  </div>
  <div class="p-8">
    <!-- 搜索区域 -->
    <div class="flex flex-wrap space-x-4 mb-4">
      <div class="flex-grow">
        <label class="block mb-1">选择查询时间：</label>
        <div class="flex space-x-2">
          <input v-model="startTime" type="date" class="w-full border border-gray-300 rounded p-2">
          <span class="self-center">至</span>
          <input v-model="endTime" type="date" class="w-full border border-gray-300 rounded p-2">
        </div>
      </div>
      <div class="flex-grow">
        <label class="block mb-1">查询患者：</label>
        <input v-model="patientName" type="text" placeholder="请输入姓名/手机/身份证" class="w-full border border-gray-300 rounded p-2">
      </div>
    </div>
    
    <div class="flex flex-wrap space-x-4 mb-4">
      <div class="flex-grow">
        <label class="block mb-1">就诊状态：</label>
        <select v-model="visitStatus" class="w-full border border-gray-300 rounded p-2">
          <option value="">请选择</option>
          <option value="1">已就诊</option>
          <option value="0">未就诊</option>
        </select>
      </div>
      <div class="flex items-end">
        <button class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600" @click="handleSearch">
          <i class="fa fa-search mr-1"></i> 查询
        </button>
        <button @click="resetInputs" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600 ml-2">
          <i class="fa fa-refresh mr-1"></i> 重置
        </button>
      </div>
    </div>
    
    <!-- 状态提示 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
    </div>
    
    <div v-else-if="errorMsg" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
      <strong class="font-bold">错误!</strong>
      <span class="block sm:inline">{{ errorMsg }}</span>
    </div>
    
    <div v-else-if="users.list.length === 0" class="text-center py-12 text-gray-500">
      <i class="fa fa-search fa-3x mb-3 text-gray-300"></i>
      <p>未找到匹配的数据</p>
    </div>
    
    <!-- 数据表格 -->
    <div v-else class="overflow-x-auto">
      <table class="w-full text-left table-auto mt-4">
        <thead>
          <tr class="bg-gray-200">
            <th class="px-4 py-2">序号</th>
            <th class="px-4 py-2">就诊状态</th>
            <th class="px-4 py-2">患者</th>
            <th class="px-4 py-2">科室ID</th>
            <th class="px-4 py-2">登记时间</th>
            <th class="px-4 py-2">接诊类型</th>
            <th class="px-4 py-2">接诊医生</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in users.list" :key="index" class="hover:bg-gray-50 transition-colors">
            <td class="border px-4 py-2">{{ index + 1 }}</td>
            <td class="border px-4 py-2">
              <span v-if="item.status === 1" class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-800">已就诊</span>
              <span v-else class="px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-800">未就诊</span>
            </td>
            <td class="border px-4 py-2">
              <div class="flex items-center">
                <div class="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center mr-2">
                  <span class="text-blue-600 font-medium"></span>
                </div>
                <span>{{ item.patient.real_name }}</span>
              </div>
            </td>
            <td class="border px-4 py-2">{{ item.doctor.department.dept_name }}</td>
            <td class="border px-4 py-2">{{ formatDate(item.create_time) }}</td>
            <td class="border px-4 py-2">
              <span v-if="item.type === 0">末诊</span>
              <span v-else>初诊</span>
            </td>
            <td class="border px-4 py-2">{{ item.doctor.real_name }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import Navigation from '@/components/Navigation.vue';
import axios from 'axios';

const url = '/prescription/findAll';
const homeRoute = '/';
const currentPage = '就诊进度';

const startTime = ref('');
const endTime = ref('');
const patientName = ref('');
const visitStatus = ref('');
const loading = ref(false);
const errorMsg = ref('');

// 原始数据和过滤后数据
const originalData = reactive({ list: [] });
const users = reactive({ list: [] });

// 页面加载时获取初始数据
const initData = async () => {
  try {
    loading.value = true;
    errorMsg.value = '';
    
    const response = await axios.get(url);
    
    if (response.status === 200) {
      originalData.list = response.data || [];
      // 初始时显示全部数据
      users.list = [...originalData.list];
    } else {
      errorMsg.value = `获取数据失败: ${response.statusText}`;
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    errorMsg.value = '获取数据出错，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString();
};

// 处理查询（前端过滤）
const handleSearch = () => {
  // 如果没有原始数据，直接返回
  if (originalData.list.length === 0) return;
  
  // 转换时间戳以便比较
  const startDate = startTime.value ? new Date(startTime.value).getTime() : null;
  const endDate = endTime.value ? new Date(endTime.value).getTime() : null;
  
  // 过滤数据
  users.list = originalData.list.filter(item => {
    // 时间过滤
    const createTime = new Date(item.create_time).getTime();
    if (startDate && createTime < startDate) return false;
    if (endDate && createTime > endDate) return false;
    
    // 患者信息过滤
    if (patientName.value) {
      const query = patientName.value.toLowerCase();
      const match = 
        (item.patient.username && item.patient.username.toLowerCase().includes(query)) ||
        (item.patient.phone && item.patient.phone.includes(query)) ||
        (item.patient.idCard && item.patient.idCard.includes(query));
      
      if (!match) return false;
    }
    
    // 就诊状态过滤
    if (visitStatus.value !== '' && item.status !== parseInt(visitStatus.value)) {
      return false;
    }
    
    return true;
  });
};

// 重置输入
const resetInputs = () => {
  startTime.value = '';
  endTime.value = '';
  patientName.value = '';
  visitStatus.value = '';
  
  // 重置为原始数据
  users.list = [...originalData.list];
};

// 页面加载完成后初始化数据
onMounted(() => {
  initData();
});
</script>

  
  <style scoped>
  .bg-white {
    background-color: #fff;
  }
  .shadow-md {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  }
  .p-4 {
    padding: 1rem;
  }
  .p-8 {
    padding: 2rem;
  }
  .text-lg {
    font-size: 1.125rem;
  }
  .text-gray-800 {
    color: #1f2937;
  }
  .flex {
    display: flex;
  }
  .flex-wrap {
    flex-wrap: wrap;
  }
  .space-x-4 > * + * {
    margin-left: 1rem;
  }
  .mb-4 {
    margin-bottom: 1rem;
  }
  .flex-grow {
    flex-grow: 1;
  }
  .block {
    display: block;
  }
  .mb-1 {
    margin-bottom: 0.25rem;
  }
  .w-full {
    width: 100%;
  }
  .border {
    border-width: 1px;
  }
  .border-gray-300 {
    border-color: #d1d5db;
  }
  .rounded {
    border-radius: 0.25rem;
  }
  .p-2 {
    padding: 0.5rem;
  }
  .self-center {
    align-self: center;
  }
  .bg-blue-500 {
    background-color: #3b82f6;
  }
  .text-white {
    color: #fff;
  }
  .py-2 {
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
  }
  .px-4 {
    padding-left: 1rem;
    padding-right: 1rem;
  }
  .hover:bg-blue-600:hover {
    background-color: #2563eb;
  }
  .bg-gray-500 {
    background-color: #6b7280;
  }
  .hover:bg-gray-600:hover {
    background-color: #4b5563;
  }
  .items-center {
    align-items: center;
  }
  .mt-4 {
    margin-top: 1rem;
  }
  table {
    border-collapse: collapse;
  }
  th, td {
    border: 1px solid #ddd;
  }
  th {
    background-color: #f0f0f0;
  }
  </style>